package com.sky.utils;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.sky.properties.HuaWeiOBSProperties;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class HuaWeiOBSUtils {
    //注入实体类参数配置
    @Autowired
    private HuaWeiOBSProperties huaWeiOBSProperties;

    /**
     * 实现上传图片到OBS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(huaWeiOBSProperties.getAccessKeyId(), huaWeiOBSProperties.getSecretAccessKey(), huaWeiOBSProperties.getEndpoint());

        try {
            // 上传文件到 OBS
            obsClient.putObject(huaWeiOBSProperties.getBucketName(), fileName, inputStream);

            // 文件访问路径
            String url = "https://" + huaWeiOBSProperties.getBucketName() + "." + huaWeiOBSProperties.getEndpoint() + "/" + fileName;

            return url; // 把上传到OBS的路径返回
        } catch (ObsException e) {
            // 处理异常
            throw new RuntimeException("上传文件失败: " + e.getMessage(), e);
        } finally {
            // 关闭obsClient
            if (obsClient != null) {
                try {
                    obsClient.close();
                } catch (Exception e) {
                    // 忽略关闭时可能产生的异常
                }
            }
        }
    }
}